package com.fone.player.play.sohu;

import java.util.Date;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.media.AudioManager;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.provider.Settings.SettingNotFoundException;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import com.fone.player.ApplicationManage;
import com.fone.player.R;
import com.fone.player.client.Error;
import com.fone.player.client.Request;
import com.fone.player.client.SohuIdRst;
import com.fone.player.entity.Download;
import com.fone.player.play.gesture.FoneOnGesture;
import com.fone.player.storage.StorageModule;
import com.fone.player.util.FoneUtil;
import com.fone.player.util.L;
import com.fone.player.util.ScreenUtil;
import com.fone.player.view.CustomAlertDialog;
import com.fone.player.view.CustomAlertDialog.Builder.CustomDialogOnClickListener;
import com.fone.player.view.CustomDialog;
import com.fone.player.view.FoneGestureOverlayView;
import com.fone.player.view.SohuVideoDefinitionPopupWindow;
import com.sohuvideo.base.log.LogManager;
import com.sohuvideo.base.widget.SohuScreenView;
import com.sohuvideo.sdk.LoadFailure;
import com.sohuvideo.sdk.PlayerError;
import com.sohuvideo.sdk.PlayerMonitor;
import com.sohuvideo.sdk.SohuLibLoadListener;
import com.sohuvideo.sdk.SohuVideoPlayer;
import com.sohuvideo.sdk.entity.SohuPlayitemBuilder;

public class SohuPlayerActivity extends Activity {
	private static final String TAG = "SohuPlayerActivity";

	/**
	 * 搜狐视频播放View
	 */
	private SohuScreenView mSohuScreenView;

	private View mControllerView, mTitleBarView, mLockView;
	private ImageView mStartPlayBtn;
	private Button mPlayOrPauseBtn;
	private Button mNextBtn;
	private Button mDefinitionBtn;
	private Button mBackBtn;
	private Button mLockBtn;
	private Button mDownBtn;
	/** 捕获手势View */
	private FoneGestureOverlayView mPlayerGestureView;
	/** 是否正在手势更改音量/亮度 */
	private boolean gestureChangeVolOrBright;
	/** 是否正在手势调节进度 */
	private boolean gestureChangeProgress;
	/** 音量百分比 */
	private int volPercentage;
	/** 最大音量，当前音量 */
	private int maxVolume, currentVolume;
	/** 显示音量调节/亮度/进度 layout */
	private View genstureLayout;
	/** 音量/亮度layout */
	private View soundBrightLayout;
	/** 音量/亮度icon */
	private ImageView ivSoundBright;
	/** 音量/亮度值 */
	private TextView tvSoundBright;
	/** 进度值 */
	private TextView tvGestureProgress;
	/** 搜狐来源 */
	private TextView tvSohuSource;
	/** 当前屏幕亮度 */
	private float currentBrightness;
	/** 音量管理器 */
	private AudioManager audiomanage;

	private SohuVideoPlayer mSohuVideoPlayer;
	private ProgressBar mProgressBar;

	private SeekBar mSeekBar;
	private TextView postionTime, durationTime, titleView;
	private boolean mTrackingTouch = false;

	private boolean lock = false;

	private SohuVideoDefinitionPopupWindow definitionPopupWindow;

	private final static int MSG_HIDE_CONTROLLER = 0;

	private String id;

	private String keyword;

	private SohuPlayitemBuilder currentPlayItem;

	/**
	 * 电池电量接收者
	 */
	private BatteryReceiver batteryReceiver;
	/**
	 * 电池状态图标
	 */
	private ImageView batteryStatus;
	/**
	 * 全屏播放时间
	 */
	private TextView fullSystemTime;
	/**
	 * 栏目id
	 */
	private int cid;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		SohuVideoPlayer.initSohuPlayer(sohuLibLoadListener, getApplicationContext());
		setContentView(R.layout.sohu_player);
		setupViews();
		initPlayerGestureListener();
		initAudioAndBrightness();
		resolveIntent();
		if (android.os.Build.VERSION.SDK_INT >= 9) {
			setRequestedOrientation(6); // ActivityInfo.SCREEN_ORIENTATION_SENSOR_LANDSCAPE
		}
		initBatteryReceiver();
	}

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_HIDE_CONTROLLER: {
				hideController();
				break;
			}
			default:
				break;
			}
		}
	};

	private SohuLibLoadListener sohuLibLoadListener = new SohuLibLoadListener() {
		@Override
		public void onProgressUpdate(long downloaded, long total) {
			LogManager.d(TAG, "onProgressUpdate, downloaded:" + downloaded + ", total:" + total);
		}

		@Override
		public void onLoadResult(boolean result) {
			LogManager.d(TAG, "onLoadResult, result:" + result);
		}

		@Override
		public void onFailed() {
			LogManager.d(TAG, "onFailed");
		}

		@Override
		public void onDownloadComplete() {
			LogManager.d(TAG, "onDownloadComplete");
			// 下载完成,重新播
			Toast.makeText(getApplicationContext(), R.string.update_player_success, Toast.LENGTH_SHORT).show();
		}

		@Override
		public void onAskForDownload() {
			Toast.makeText(getApplicationContext(), R.string.update_player_lib_toast, Toast.LENGTH_SHORT).show();
			SohuVideoPlayer.onDownloadLibComfirm(true);
		}

		@Override
		public void onDownloadCancel() {
		}
	};

	private void setupViews() {
		mStartPlayBtn = (ImageView) findViewById(R.id.btn_start_play);
		mStartPlayBtn.setOnClickListener(mOnClickListener);
		mPlayOrPauseBtn = (Button) findViewById(R.id.full_player_play_pause);
		mPlayOrPauseBtn.setOnClickListener(mOnClickListener);

		mNextBtn = (Button) findViewById(R.id.full_player_next);
		mNextBtn.setOnClickListener(mOnClickListener);

		mBackBtn = (Button) findViewById(R.id.player_back_full);
		mBackBtn.setOnClickListener(mOnClickListener);

		mDefinitionBtn = (Button) findViewById(R.id.full_player_definition);
		mDefinitionBtn.setOnClickListener(mOnClickListener);

		mLockBtn = (Button) findViewById(R.id.player_full_lock);
		mLockBtn.setOnClickListener(mOnClickListener);

		mSohuScreenView = (SohuScreenView) findViewById(R.id.sohu_screen);
		mSohuScreenView.setOnClickListener(mOnClickListener);
		mControllerView = findViewById(R.id.controller);
		mTitleBarView = findViewById(R.id.titlebar);
		mLockView = findViewById(R.id.full_player_left);

		mSeekBar = (SeekBar) findViewById(R.id.full_player_seekbar);
		mSeekBar.setOnSeekBarChangeListener(mOnSeekBarChangeListener);

		postionTime = (TextView) findViewById(R.id.full_player_play_progress);
		postionTime.setText("00:00");
		durationTime = (TextView) findViewById(R.id.full_player_play_duration);
		durationTime.setText("00:00");

		titleView = (TextView) findViewById(R.id.player_title_full);
		tvSohuSource = (TextView) findViewById(R.id.full_player_source);
		tvSohuSource.setOnClickListener(mOnClickListener);

		// mFastForwardBtn = (ImageView) findViewById(R.id.btn_fast_forward);
		// mFastForwardBtn.setOnClickListener(mOnClickListener);
		// mFastBackwardBtn = (ImageView) findViewById(R.id.btn_fast_backward);
		// mFastBackwardBtn.setOnClickListener(mOnClickListener);

		mProgressBar = (ProgressBar) findViewById(R.id.progressbar);
		mProgressBar.setVisibility(View.GONE);

		mPlayerGestureView = (FoneGestureOverlayView) findViewById(R.id.full_surface_gesture);
		genstureLayout = findViewById(R.id.full_player_gensture_layout);
		soundBrightLayout = findViewById(R.id.video_full_vol_layout);
		ivSoundBright = (ImageView) findViewById(R.id.video_full_vol_icon);
		tvSoundBright = (TextView) findViewById(R.id.video_full_vol_text);
		tvGestureProgress = (TextView) findViewById(R.id.video_full_postion_text);
		batteryStatus = (ImageView) findViewById(R.id.player_battery_full);
		fullSystemTime = (TextView) findViewById(R.id.player_time_full);
		fullSystemTime.setText(FoneUtil.formatDate(new Date(), "HH:mm"));
		mDownBtn = (Button) findViewById(R.id.sohu_player_download);
		mDownBtn.setOnClickListener(mOnClickListener);
	}

	/**
	 * 初始化音量和亮度
	 * 
	 * @return void
	 * @throws
	 */
	private void initAudioAndBrightness() {
		audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
		maxVolume = audiomanage.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_MUSIC);
		volPercentage = (int) (((double) currentVolume / (double) maxVolume) * 100);
		try {
			currentBrightness = (float) Settings.System.getInt(getContentResolver(), Settings.System.SCREEN_BRIGHTNESS) / 255f;
		} catch (SettingNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化电池电量接收
	 * 
	 * @return void
	 * @throws
	 */
	private void initBatteryReceiver() {
		batteryReceiver = new BatteryReceiver();
		IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
		registerReceiver(batteryReceiver, filter);
	}

	/**
	 * 电池电量广播接收者
	 * 
	 * @author kongxiaojun
	 * @since 2014-9-2
	 */
	private class BatteryReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			// 判断它是否是为电量变化的Broadcast Action
			if (Intent.ACTION_BATTERY_CHANGED.equals(intent.getAction())) {
				// 获取当前电量
				int level = intent.getIntExtra("level", 0);
				// 电量的总刻度
				int scale = intent.getIntExtra("scale", 100);
				// 电池状态
				int status = intent.getIntExtra("status", -1);
				// 把它转成百分比
				// tv.setText("电池电量为"+((level*100)/scale)+"%");
				switch (status) {
				case BatteryManager.BATTERY_STATUS_CHARGING: {// 充电中
					batteryStatus.setImageResource(R.drawable.player_batter_charging);
					break;
				}
				default: {
					// 计算电池电量百分比显示对应的状态图
					int percentage = (level * 100) / scale;
					if (percentage > 75) {
						// 显示满格
						batteryStatus.setImageResource(R.drawable.player_battery_full);
					} else if (percentage > 35) {
						// 显示中格
						batteryStatus.setImageResource(R.drawable.player_battery_middle);
					} else {
						// 显示低电量
						batteryStatus.setImageResource(R.drawable.player_battery_low);
					}
					break;
				}
				}
			}
		}

	}

	private OnSeekBarChangeListener mOnSeekBarChangeListener = new OnSeekBarChangeListener() {
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
			LogManager.d(TAG, "onStopTrackingTouch");
			mTrackingTouch = false;
			int whereto = seekBar.getProgress();
			if (whereto > 0) {
				mSohuVideoPlayer.seekTo(whereto);
			}
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
			LogManager.d(TAG, "onStartTrackingTouch");
			mTrackingTouch = true;
		}

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			LogManager.d(TAG, "onProgressChanged, progress:" + progress + ", fromUser:" + fromUser);
			long duration = mSohuVideoPlayer.getDuration();
			long temp = (duration * progress) / 1000;
			LogManager.i(TAG, "duration:" + duration + ", progress:" + progress + ", temp:" + temp);
			String timeStr = FoneUtil.second2MinuteStr((int) (temp / seekBar.getMax()));
			postionTime.setText(timeStr);
		}
	};

	/**
	 * 初始化播放器
	 * 
	 * @return void
	 * @throws
	 */
	private void initPlayer() {
		mSohuVideoPlayer = new SohuVideoPlayer(this);
		mSohuVideoPlayer.setSohuScreenView(mSohuScreenView);
		mSohuVideoPlayer.setPlayerMonitor(mPlayerMonitor);
	}

	/**
	 * Override methods if needed.
	 */
	private PlayerMonitor mPlayerMonitor = new PlayerMonitor() {

		@Override
		public void onPreparing() {
			super.onPreparing();
			mStartPlayBtn.setVisibility(View.GONE);
			mProgressBar.setVisibility(View.VISIBLE);
		}

		@Override
		public void onPrepared() {
			super.onPrepared();
			mPlayOrPauseBtn.setBackgroundResource(R.drawable.video_fullscreen_pause_selector);
			mProgressBar.setVisibility(View.GONE);
			durationTime.setText(FoneUtil.second2MinuteStr(mSohuVideoPlayer.getDuration() / 1000));
			updateDefinition(mSohuVideoPlayer.getCurrentDefinition());
			mHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROLLER, 3000);
			mSeekBar.setMax(mSohuVideoPlayer.getDuration());
		}

		@Override
		public void onPlay() {
			super.onPlay();
			mPlayOrPauseBtn.setBackgroundResource(R.drawable.video_fullscreen_pause_selector);
			mHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROLLER, 3000);
		}

		@Override
		public void onPause() {
			super.onPause();
			mPlayOrPauseBtn.setBackgroundResource(R.drawable.video_fullscreen_play_selector);
		}

		@Override
		public void onStop() {
			super.onStop();
			mPlayOrPauseBtn.setBackgroundResource(R.drawable.video_fullscreen_play_selector);
		}

		@Override
		public void onError(PlayerError error) {
			L.v(TAG, error.toString());
		}

		@Override
		public void onStartLoading() {
			super.onStartLoading();
			mProgressBar.setVisibility(View.VISIBLE);
		}

		@Override
		public void onLoadSuccess() {
			super.onLoadSuccess();
		}

		@Override
		public void onLoadFail(LoadFailure failure) {

		}

		@Override
		public void onBuffering(int progress) {
			super.onBuffering(progress);
			mProgressBar.setVisibility(View.VISIBLE);
		}

		@Override
		public void onComplete() {
			super.onComplete();
			SohuPlayerActivity.this.finish();
		}

		@Override
		public void onPausedAdvertShown() {
			super.onPausedAdvertShown();
			hideController();
			mHandler.removeMessages(MSG_HIDE_CONTROLLER);
		}

		@Override
		public void onProgressUpdated(int currentPostion, int duration) {
			mProgressBar.setVisibility(View.GONE);
			if (mTrackingTouch || gestureChangeProgress) {
				return;
			}
			if (currentPostion >= 0) {
				mSeekBar.setProgress(currentPostion);
			}
			postionTime.setText(FoneUtil.second2MinuteStr(currentPostion / 1000));
		}

		@Override
		public void onVideoClick() {
		}

		@Override
		public void onDecodeChanged(boolean arg0, int arg1, int arg2) {
			super.onDecodeChanged(arg0, arg1, arg2);
		}

		@Override
		public void onDefinitionChanged() {
			super.onDefinitionChanged();
			updateDefinition(mSohuVideoPlayer.getCurrentDefinition());
		}

		@Override
		public void onPlayItemChanged(SohuPlayitemBuilder arg0, int arg1) {
			super.onPlayItemChanged(arg0, arg1);
			currentPlayItem = arg0;
			titleView.setText(arg0.getTitle());
		}

		@Override
		public void onPlayOver(SohuPlayitemBuilder arg0) {
			super.onPlayOver(arg0);
		}

		@Override
		public void onPreviousNextStateChange(boolean arg0, boolean arg1) {
			super.onPreviousNextStateChange(arg0, arg1);
		}

	};

	@Override
	protected void onResume() {
		super.onResume();
		if (mSohuVideoPlayer != null) {
			mSohuVideoPlayer.play();
		}
	}

	@Override
	protected void onPause() {
		super.onPause();
		if (mSohuVideoPlayer != null) {
			mSohuVideoPlayer.pause();
		}
	}

	@Override
	protected void onStop() {
		super.onStop();
		if (mSohuVideoPlayer != null) {
			mSohuVideoPlayer.stop(true);
		}
	}

	@Override
	protected void onDestroy() {
		if (mSohuVideoPlayer != null) {
			mSohuVideoPlayer.stop(false);
			mSohuVideoPlayer.release();
		}
		super.onDestroy();
	}

	private View.OnClickListener mOnClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.btn_start_play: { // 点击播放
				if (mSohuVideoPlayer != null) {
					mSohuVideoPlayer.play();
					sendHideControllerMessge();
				}
				break;
			}
			case R.id.full_player_play_pause: { // 点击播放/暂停
				if (mSohuVideoPlayer != null) {
					mSohuVideoPlayer.playOrPause();
					sendHideControllerMessge();
				}
				break;
			}
			case R.id.full_player_next: { // 点击下一集
				if (currentPlayItem != null && currentPlayItem.getTvId() <= 0 && mSohuVideoPlayer != null) {
					mSohuVideoPlayer.next();
					sendHideControllerMessge();
				}
				break;
			}

			case R.id.player_back_full: { // 点击返回
				SohuPlayerActivity.this.finish();
				break;
			}

			case R.id.player_full_lock: { // 点击锁定
				lock = !lock;
				mLockBtn.setBackgroundResource(lock ? R.drawable.video_fullscreen_lock_selector : R.drawable.video_fullscreen_unlock_selector);
				if (lock) {
					mControllerView.setVisibility(View.GONE);
					mTitleBarView.setVisibility(View.GONE);
				} else {
					showController();
				}
				sendHideControllerMessge();
				break;
			}
			case R.id.full_player_definition: { // 点击清晰度
				showDefinitionWindow(v);
				sendHideControllerMessge();
				break;
			}
			case R.id.full_player_source: { // 点击下载搜狐apk

				// 是否已经安装了搜狐app
				if (FoneUtil.checkApkExist(SohuPlayerActivity.this, AppConst.SOHU_APP_PACKAGENAME) != null) {
					FoneUtil.start3rdApp(SohuPlayerActivity.this, AppConst.SOHU_APP_PACKAGENAME);
					return;
				}

				startDownloadSohuApp();

				break;
			}
			case R.id.sohu_player_download: {// 缓存
				// 检测是否安装搜狐视频，已经安装了就打开搜狐视频详情页，未安装就提示安装
				if (FoneUtil.checkApkExist(SohuPlayerActivity.this, AppConst.SOHU_APP_PACKAGENAME) != null) {
					// 已安装搜狐视频
					StringBuffer sb = new StringBuffer();
					sb.append("sva:// action.cmd?action=1.1");
					sb.append("&cid=").append(cid);
					if (currentPlayItem.getSid() != 0) {
						sb.append("&sid=");
						sb.append(currentPlayItem.getSid());
					}
					if (currentPlayItem.getVid() != 0) {
						sb.append("&vid=");
						sb.append(currentPlayItem.getVid());
					}
					if (currentPlayItem.getSite() != 0) {
						sb.append("&site=");
						sb.append(currentPlayItem.getSite());
					}
					sb.append("&channelid=1000120021&paused=1&backpage=1&ex1=测试用");
					String data = sb.toString();
					Intent intent = new Intent(Intent.ACTION_DEFAULT);
					intent.setData(Uri.parse(data));
					startService(intent);
				} else {
					// 未安装搜狐视频
					new CustomAlertDialog.Builder(SohuPlayerActivity.this, getString(R.string.dialog_title), getString(R.string.sohu_video_cache_install_sohuvideo), getString(R.string.dialog_cancel), getString(R.string.dialog_ok), new CustomDialogOnClickListener() {
						@Override
						public void onRight() {
							startDownloadSohuApp();
						}

						@Override
						public void onLeft() {
						}
					}).create().show();
				}
				break;
			}
			/*
			 * case R.id.btn_prev: { break; } case R.id.btn_next: { break; }
			 */
			default:
				break;
			}
		}
	};

	/**
	 * 显示清晰度选择框
	 * 
	 * @param v
	 * @return void
	 * @throws
	 */
	private void showDefinitionWindow(View v) {
		if (definitionPopupWindow == null) {
			definitionPopupWindow = new SohuVideoDefinitionPopupWindow(SohuPlayerActivity.this, mSohuVideoPlayer.getSupportDefinitions(), new SohuVideoDefinitionPopupWindow.ItemClickCallBack() {
				@Override
				public void onItemclick(Integer dfnt) {
					// 切换清晰度
					if (dfnt != mSohuVideoPlayer.getCurrentDefinition()) {
						mSohuVideoPlayer.changeDefinition(dfnt);
						// 更新清晰度背景
						updateDefinition(dfnt);
					}
					if (definitionPopupWindow != null) {
						definitionPopupWindow.dismiss();
					}

				}
			}, mSohuVideoPlayer.getCurrentDefinition());
		} else {
			definitionPopupWindow.setDfntList(mSohuVideoPlayer.getSupportDefinitions(), mSohuVideoPlayer.getCurrentDefinition());
		}
		if (definitionPopupWindow.isShowing()) {
			definitionPopupWindow.dismiss();
		} else {
			definitionPopupWindow.show(v);
		}
	}

	/**
	 * 开始下载搜狐视频客户端
	 * 
	 * @return void
	 * @throws
	 */
	protected void startDownloadSohuApp() {
		Download download = new Download();
		download.setDownloadIsShowRunningNotification(true);
		download.setDownloadUrl(AppConst.SOHU_APK_URL);
		download.setDownloadFileName("搜狐视频");
		download.setDownloadNotification(SohuPlayerActivity.this);
		download.setDownloadIsInstall(true);
		download.setDownloadIsErrorToast(true);
		download.setDownloadIsLimitSpeed(false);
		download.setDownloadType(Download.DOWNLOAD_RECOMMEND);
		int result = StorageModule.getInstance().addFileDownload(download);
		switch (result) {
		case 1:
			FoneUtil.showToast(SohuPlayerActivity.this, "已经开始下载搜狐视频");
			break;
		case -1:
			FoneUtil.showToast(SohuPlayerActivity.this, "该任务已下载");
			break;
		default:
			break;
		}
	}

	/**
	 * 更新清晰度背景
	 * 
	 * @param dfnt
	 * @return void
	 * @throws
	 */
	private void updateDefinition(int dfnt) {
		mDefinitionBtn.setVisibility(View.VISIBLE);
		switch (dfnt) {
		case 1:// 标清
			mDefinitionBtn.setBackgroundResource(R.drawable.full_icon_play_control_standard);
			break;
		case 2:// 高清
			mDefinitionBtn.setBackgroundResource(R.drawable.full_icon_play_control_high);
			break;
		case 4:// 超清
			mDefinitionBtn.setBackgroundResource(R.drawable.full_icon_play_control_supper);
			break;
		default:
			break;
		}
	}

	/**
	 * 隐藏控制区layout
	 * 
	 * @return void
	 * @throws
	 */
	private void hideController() {
		mControllerView.setVisibility(View.GONE);
		mTitleBarView.setVisibility(View.GONE);
		mLockView.setVisibility(View.GONE);
		if (definitionPopupWindow != null && definitionPopupWindow.isShowing()) {
			definitionPopupWindow.dismiss();
		}
		mDownBtn.setVisibility(View.GONE);
	}

	/**
	 * 显示控制区layout
	 * 
	 * @return void
	 * @throws
	 */
	private void showController() {
		if (lock) {
			mLockView.setVisibility(View.VISIBLE);
			Toast.makeText(getApplicationContext(), R.string.unlock_text, Toast.LENGTH_SHORT).show();
		} else {
			mControllerView.setVisibility(View.VISIBLE);
			mTitleBarView.setVisibility(View.VISIBLE);
			mLockView.setVisibility(View.VISIBLE);
			// 显示最新时间
			fullSystemTime.setText(FoneUtil.formatDate(new Date(), "HH:mm"));
			mDownBtn.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * 发送隐藏控制区layout消息
	 * 
	 * @return void
	 * @throws
	 */
	private void sendHideControllerMessge() {
		mHandler.removeMessages(MSG_HIDE_CONTROLLER);
		mHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROLLER, 3000);
	}

	private void resolveIntent() {
		// Intent intent = new Intent();
		Intent intent = getIntent();
		id = intent.getStringExtra(AppConst.INTENT_KEY_ID);
		if (TextUtils.isEmpty(id)) {
			id = "111";
		}
		keyword = intent.getStringExtra(AppConst.INTENT_KEY_KEYWORD);
		if (TextUtils.isEmpty(keyword)) {
			keyword = "test";
		}
		String ourl = intent.getStringExtra(AppConst.INTENT_KEY_OURL);
		if (TextUtils.isEmpty(ourl)) {
			L.v(TAG, getString(R.string.ourl_null));
			finish();
			return;
		}
		mProgressBar.setVisibility(View.VISIBLE);
		Request.getInstance().getSohuIds(ourl, new com.fone.player.client.Callback<SohuIdRst>() {
			@Override
			public void onSuccess(SohuIdRst t) {
				if (t.result == 0) {
					initPlayer();
					cid = t.idlist.cid;
					// 成功
					int tvid = t.idlist.tvid;
					if (tvid > 0) {
						mSohuVideoPlayer.setDataSource(new SohuPlayitemBuilder(id, tvid), keyword);
						mSohuVideoPlayer.play();
						return;
					}
					long sid = t.idlist.sid;
					long vid = t.idlist.vid;
					int site = t.idlist.site;
					if (sid > 0 || vid > 0) {
						if (site > 0) {
							mSohuVideoPlayer.setDataSource(new SohuPlayitemBuilder(id, sid, vid).setSite(site), keyword);
						} else {
							mSohuVideoPlayer.setDataSource(new SohuPlayitemBuilder(id, sid, vid), keyword);
						}
						SohuVideoPlayer.setArgs(AppConst.FONE_APPKEY, AppConst.TEST_PARTNER, getApplicationContext());
						mSohuVideoPlayer.play();
					}
				} else {
					mProgressBar.setVisibility(View.GONE);
					Toast.makeText(getApplicationContext(), R.string.video_cannot_cache, Toast.LENGTH_SHORT).show();
				}
			}

			@Override
			public void onFailure(Error error) {
				mProgressBar.setVisibility(View.GONE);
				Toast.makeText(getApplicationContext(), error.getReason(), Toast.LENGTH_SHORT).show();
			}
		});

	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:// 返回键
			if (lock) {
				return true;
			}
			break;

		default:
			break;
		}

		return super.onKeyDown(keyCode, event);

	}

	/**
	 * 初始化手势监听
	 */
	private void initPlayerGestureListener() {

		L.v(TAG, "initPlayerGestureListener", "start");
		FoneOnGesture foneOnGesture = new FoneOnGesture();
		foneOnGesture.setFoneOnGestureListener(new FoneOnGesture.FoneOnGestureListener() {

			@Override
			public void FoneOnGestureStart() {
				L.v(TAG, "initPlayerGestureListener", "FoneOnGestureStart");
				mHandler.removeCallbacks(hideGenstureLayoutRunnable);
			}

			int width;

			@Override
			public void FoneOnGestureMoveUPOrDown(boolean isEnableSeek, float distance, float start_x, boolean two_pointer) {
				if (!lock) {
					L.v(TAG, "initPlayerGestureListener", "FoneOnGestureMoveUPOrDown");
					L.v(TAG, "initPlayerGestureListener", "isEnableSeek=" + isEnableSeek + "  distance=" + distance + "  start_x=" + start_x + "  two_pointer=" + two_pointer);
					if (width == 0) {
						width = ScreenUtil.getScreenWidthPix(SohuPlayerActivity.this);
					}
					gestureChangeVolOrBright = true;
					// 修改音量/亮度
					int status = (width / 2 < start_x) ? 2 : 1;
					if (status == 1) {
						// 修改音量
						int addVol = (int) (distance / (ScreenUtil.getScreenHeightPix(SohuPlayerActivity.this) / 50));
						volPercentage -= addVol;
						currentVolume = (int) (((double) volPercentage / 100) * maxVolume);
						if (volPercentage >= 100) {
							volPercentage = 100;
							currentVolume = maxVolume;
						}
						if (volPercentage <= 0) {
							volPercentage = 0;
							currentVolume = 0;
						}
						updateVolume();
					} else {
						// 修改亮度
						float addBright = distance / (float) (ScreenUtil.getScreenHeightPix(SohuPlayerActivity.this) * 10);
						currentBrightness -= addBright;
						if (currentBrightness >= 1) {
							currentBrightness = 1;
						}
						if (currentBrightness <= 0) {
							currentBrightness = 0;
						}
						updateBright();
					}

				}
			}

			@Override
			public void FoneOnGestureMovePrevious() {
				L.v(TAG, "initPlayerGestureListener", "FoneOnGestureMovePrevious");
				// onPlayerPreviousAction();
			}

			@Override
			public void FoneOnGestureMoveNext() {
				L.v(TAG, "initPlayerGestureListener", "FoneOnGestureMoveNext");
				// onPlayerNextAction();
			}

			int currentProgress;

			@Override
			public void FoneOnGestureMoveLeftOrRight(boolean isEnableSeek, float eventY, float distance) {
				if (!lock) {
					L.v(TAG, "initPlayerGestureListener", "FoneOnGestureMoveLeftOrRight");
					try {
						if (mSohuVideoPlayer != null && mSohuVideoPlayer.getDuration() > 0) {
							int videoDruation = mSohuVideoPlayer.getDuration();
							if (videoDruation > 0) {
								// 调节进度
								gestureChangeProgress = true;
								currentProgress = mSohuVideoPlayer.getCurrentPosition();
								L.v(TAG, "FoneOnGestureMoveLeftOrRight currentProgress start : " + currentProgress);
								// 每滑动10像素加1秒
								currentProgress -= distance / 10 * 1000;
								L.v(TAG, "FoneOnGestureMoveLeftOrRight currentProgress computed : " + currentProgress);
								if (currentProgress <= 0) {
									currentProgress = 0;
								}
								if (currentProgress >= videoDruation) {
									currentProgress = videoDruation;
								}
								L.v(TAG, "FoneOnGestureMoveLeftOrRight currentProgress compute end : " + currentProgress);
								L.v(TAG, "FoneOnGestureMoveLeftOrRight videoDruation : " + videoDruation);
								gestureUpdateProgress(currentProgress);
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			}

			@Override
			public void FoneOnGestureEnd(boolean isEnableSeek, boolean isLeftOrRight) {
				L.v(TAG, "initPlayerGestureListener", "FoneOnGestureEnd isEnableSeek: " + isEnableSeek + " ,isLeftOrRight:" + isLeftOrRight);
				if (!gestureChangeVolOrBright && !gestureChangeProgress) {
					// 单击
					if (lock && mLockView.getVisibility() != View.VISIBLE) {
						Toast.makeText(SohuPlayerActivity.this, R.string.unlock_text, Toast.LENGTH_SHORT).show();
					}
					if (mLockView.getVisibility() == View.VISIBLE) {
						mHandler.removeMessages(MSG_HIDE_CONTROLLER);
						hideController();
					} else {
						showController();
						mHandler.sendEmptyMessageDelayed(MSG_HIDE_CONTROLLER, 3000);
					}
					mHandler.postDelayed(hideGenstureLayoutRunnable, 2000);
				} else {
					mHandler.post(gestureEndRun);
				}
			}

			/**
			 * 单击时运行
			 */
			Runnable gestureEndRun = new Runnable() {
				@Override
				public void run() {
					if (gestureChangeVolOrBright || gestureChangeProgress) {
						if (gestureChangeProgress) {
							mSohuVideoPlayer.seekTo(currentProgress);
						}
						gestureChangeVolOrBright = false;
						gestureChangeProgress = false;
					}
					mHandler.postDelayed(hideGenstureLayoutRunnable, 2000);
				}
			};

			@Override
			public void FoneOnGesture() {
			}
		});

		mPlayerGestureView.addOnGestureListener(foneOnGesture);

	}

	/**
	 * 更新音量
	 * 
	 * @return void
	 * @throws
	 */
	private void updateVolume() {
		mHandler.removeCallbacks(hideGenstureLayoutRunnable);
		genstureLayout.setVisibility(View.VISIBLE);
		soundBrightLayout.setVisibility(View.VISIBLE);
		ivSoundBright.setVisibility(View.VISIBLE);
		tvSoundBright.setVisibility(View.VISIBLE);
		tvGestureProgress.setVisibility(View.GONE);

		audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC, currentVolume, 0);
		if (volPercentage == 0) {
			ivSoundBright.setImageResource(R.drawable.full_icon_gesture_sound_un);
		} else {
			ivSoundBright.setImageResource(R.drawable.full_icon_gesture_sound);
		}
		tvSoundBright.setText(volPercentage + "%");
	}

	/**
	 * 隐藏 音量/亮度/进度显示区
	 */
	private Runnable hideGenstureLayoutRunnable = new Runnable() {

		@Override
		public void run() {
			genstureLayout.setVisibility(View.GONE);
		}
	};

	/**
	 * 更新亮度
	 * 
	 * @return void
	 * @throws
	 */
	private void updateBright() {
		mHandler.removeCallbacks(hideGenstureLayoutRunnable);
		genstureLayout.setVisibility(View.VISIBLE);
		soundBrightLayout.setVisibility(View.VISIBLE);
		ivSoundBright.setVisibility(View.VISIBLE);
		tvSoundBright.setVisibility(View.VISIBLE);
		tvGestureProgress.setVisibility(View.GONE);
		ivSoundBright.setImageResource(R.drawable.full_icon_gesture_bright);

		WindowManager.LayoutParams lp = getWindow().getAttributes();
		lp.screenBrightness = currentBrightness;
		getWindow().setAttributes(lp);

		tvSoundBright.setText((int) (currentBrightness * 100) + "%");
	}

	/**
	 * 更新进度
	 * 
	 * @param currentProgress
	 * @return void
	 * @throws
	 */
	protected void gestureUpdateProgress(int currentProgress) {
		L.v(TAG, "gestureUpdateProgress");
		mHandler.removeCallbacks(hideGenstureLayoutRunnable);
		tvGestureProgress.setText("");
		genstureLayout.setVisibility(View.VISIBLE);
		soundBrightLayout.setVisibility(View.GONE);
		ivSoundBright.setVisibility(View.GONE);
		tvGestureProgress.setVisibility(View.VISIBLE);
		String curStr = FoneUtil.second2MinuteStr(currentProgress / 1000);
		String durStr = FoneUtil.second2MinuteStr(mSohuVideoPlayer.getDuration() % 1000 > 0 ? mSohuVideoPlayer.getDuration() / 1000 + 1 : mSohuVideoPlayer.getDuration() / 1000);
		SpannableString ss = new SpannableString(curStr);
		ss.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.video_info_tab_line)), 0, curStr.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		tvGestureProgress.append(ss);
		ss = new SpannableString("/" + durStr);
		ss.setSpan(new ForegroundColorSpan(Color.WHITE), 0, durStr.length() + 1, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
		tvGestureProgress.append(ss);
		mSeekBar.setProgress(currentProgress);
	}
}
